#!/usr/bin/env python
# -*- coding: utf-8 -*-
from trest.utils import utime
from trest.logger import SysLogger
from trest.config import settings
from trest.exception import JsonError
from applications.common.models.idiom_input import IdiomInput


class IdiomInputService(object):

    @staticmethod
    def count_input(word):
        """统计用户输入不在idiom表里面的词
        """
        # 中文字个数小于3，不统计
        count_len = IdiomInputService._count_num(word)
        if count_len < 3:
            return

        obj = IdiomInput.Update.filter(IdiomInput.word == word).first()
        try:
            print('obj ', type(obj), obj)
            SysLogger.error(f'{obj}  word: {word}')
            if obj:
                param = {
                    'count': obj.count + 1,
                    'updated_at': utime.timestamp(3),
                }
                IdiomInput.Update.filter(IdiomInput.word == word).update(param)
            else:
                param = {
                    'word': word,
                    'created_at': utime.timestamp(3),
                }
                obj = IdiomInput(**param)
                IdiomInput.session.add(obj)
            IdiomInput.session.commit()
            return True
        except Exception as e:
            IdiomInput.session.rollback()
            SysLogger.error(e)
        return True

    @staticmethod
    def _count_num(word):
        """输入一行字符，分别统计出其中中文字符的个数
        """
        count = 0
        for char in word:
            # 判断是否是汉字，在isalpha()方法之前判断
            # char.isalpha() 汉字也返回true
            if u'\u4e00' <= char <= u'\u9fa5':
                count += 1
        return count
